/**
 * @author wqs
 * @desc Record js
 * @datatime 2018年4月19日16:04:50
 */

function setOptions() {
  return {
    duration: 60000,
    sampleRate: 16000,
    numberOfChannels: 1,
    encodeBitRate: 48000,
    format: 'mp3'
  }
}

//检查授权
function checkAuth() {
  return new Promise((resolve, reject) => {
    wx.authorize({
      scope: 'scope.record',
      success: function (res) {
        resolve();
      },
      fail: function (res) {
        //如果拒绝过授权
        wx.openSetting({
          success: (res) => {
            res.authSetting = {
              "scope.record": true
            }
          }
        });
        reject();
      },
      complete: function (res) { },
    })
  })
}


/***
 * @desc 录音最小时间
 */
function recordTime(callBack){
  //时间大于1s
  var timeOut = setTimeout(() => {
    clearTimeout(timeOut);
    if ("function" === typeof (callBack)) {
      callBack();
    }
  }, 1000)//录音时间大于1s
}

function RecorderManager(options) {
  this.record = wx.getRecorderManager();
  this.options = options || setOptions();
  this.isStop = false;
  this.isMinTime = true;
}

RecorderManager.prototype.start = function () {
  checkAuth()
    .then(res=>{
      this.record.start(this.options);
      recordTime(()=>{
        this.isMinTime = false; 
      })
    })
    .catch(err=>{
      this.record.stop();
    })

}

RecorderManager.prototype.onStart = function (callBack) {
  if ("function" === typeof (callBack)) {
    this.record.onStart(res=>{
      if (this.isStop) {
        this.record.stop();
        return;
      }
      callBack(res);
    })
  }
}

RecorderManager.prototype.stop = function () {
  this.record.stop();
  this.isStop = true;
}

RecorderManager.prototype.done = function (callBack) {
  if ("function" === typeof (callBack)) {
    this.record.onStop((res) => {
      if (this.isMinTime) {
        callBack({
          msg:'录音时间太短',
          status:0
        });
        return;
      }
      res.fileName = `${new Date().getTime()}.${this.options.format}`;
      res.size = res.fileSize;
      res.duration = Math.ceil(res.duration/1000);
      res.path = res.tempFilePath;
      callBack(res);
    })
  }
}

RecorderManager.prototype.cancel = function (callBack) {
  this.record.stop();
  if ("function" === typeof (callBack)) {
    callBack({
      msg: 'stop ok'
    });
  }
}

RecorderManager.prototype.onError = function (callBack) {
  if ("function" === typeof (callBack)) {
    this.record.onError((err) => {
      console.error('record err', err);
      callBack(err);
    });

  }
}

module.exports = RecorderManager
